// pages/module/createLive/createLive.js
import regeneratorRuntime from '../../../utils/runtime.js';
import util from '../../../utils/util.js';
import {
	getData,
	setData,
	clearData,
	dataKey
} from '../../../utils/storage.js';
import shareFun from '../../../utils/shareFun.js';
import {
	uploadFile
} from '../../../utils/upload.js';
import dateTimePicker from '../../../utils/dateTimePicker.js';
import WeCropper from '../../../dist/we-cropper.min.js';
import {
	hostCheck,
	refreshInfo,
	creatLive,
	cherckMineInfo,
	getLiveClassify,
	visitList,
} from '../../../utils/imapi.js';

var app = getApp();
const device = wx.getSystemInfoSync() // 获取设备信息
const width = device.windowWidth
const height = device.windowHeight - 100;
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		startTime: '',
		endTime: '',
		live_title: '',
		live_list: [],
		live_index: -1,
		numList: [{
			name: '基本资料'
		}, {
			name: '保证金'
		}, {
			name: '平台审核'
		}],
		step_num: 0,
		is_select: 0,
		is_go_auth: false,
		status: '审核中…',
		status_con: "您的主播认证正在审核中，请耐心等待",
		time3: undefined,
		timeStr3: '',
		timeStr4: '',
		timeShow3: false,
		rangeStart: undefined,
		rangeEnd: undefined,
		img_list: {},
		is_load_live_cover: false,
		is_load_share_cover: false,
		liveImg: '',
		shareImg: '',
		is_test: false,
		test_live_id: 1294825775693828096,
		image_index:0, //要上传图片的下标
		xd: true, //选择默认还是自己上传的图
		test1: 0, //图片选中的下标
		date: '', //选择的时间
		default_share_imgs: [], //样式图片
		img1: '', //选中的默认图片
		ne: '', //选中日期的毫秒数
		dateTimeArray1: null,
		dateTime1: null,
		wx_no: "", //主播微信号
		sub_wx_no: '', //主播微信号
		userInfo: "", //主播信息
		is_host: 0,
		showWeCropper: false,
		    cropperOpt: {
		      id: 'cropper',
		      width,
		      height,
		      scale: 2.5,
		      zoom: 8,
		      cut: {
		        x: (width - 300) / 2,
		        y: (height - 300) / 2,
		        width: 300,
		        height: 300
		      }
		    },
			avatar: 'https://sucai.suoluomei.cn/sucai_zs/images/20200516105950-2.png',
			
			sub_anchor_qr:'',// 副微信号 扫描登陆的QR
			sub_anchor_disable:false, //副微信号 检测实名后  就不让再修改了， 如果需要修改那么重新创建
			sub_is_authed:false, //实名是否已经检测, 当副微信号不为空并且 sub_is_authed 为 true 才往下走
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function(options) {

		this.setData({
			img_list: util.img_list
		})

		shareFun.hidenShareMenu();
		this.is_back = false;
		this.is_upload = false;
		var wx_no = "",
			is_host = 0;
		this.type = 'start';
		let date = new Date();
		this.setData({
			rangeStart: date.getTime()
		});
		date.setDate(date.getDate() + 90);
		this.setData({
			rangeEnd: date.getTime()
		})

		this.setData({

			userInfo:app.globalData.userInfo
		})

		try {
			wx_no = app.globalData.userInfo.anchor_wechat_no
			is_host = app.globalData.userInfo.is_anchor_auth
		} catch (error) {

		}

		 if(wx_no){
		   this.data.wx_no = wx_no;
		   this.setData({
		     is_host:is_host,
		     wx_no:wx_no,
		   })
			console.log(this.data.is_host);
		 } else {
		   const mineInfo = await cherckMineInfo()

		   app.globalData.userInfo.wechat_alian_no = mineInfo.data.anchor_wechat_no
		   app.globalData.userInfo.is_anchor_auth = mineInfo.data.is_anchor_auth
		   this.setData({
		     is_host:mineInfo.data.is_anchor_auth,
		     wx_no:mineInfo.data.anchor_wechat_no,
		   })
			console.log(this.data.is_host);
		 }


		const {
			data
		} = await getLiveClassify();
		console.log(data);
		this.setData({
			live_list: data
		})

		var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
		var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
		// 精确到分的处理，将数组的秒去掉
		var lastArray = obj1.dateTimeArray.pop();
		var lastTime = obj1.dateTime.pop();

		this.setData({
			dateTimeArray1: obj1.dateTimeArray,
			dateTime1: obj1.dateTime,
		});

		var ne1 = this.data.dateTimeArray1[0][this.data.dateTime1[0]];
		var ne2 = this.data.dateTimeArray1[1][this.data.dateTime1[1]];
		var ne3 = this.data.dateTimeArray1[2][this.data.dateTime1[2]];
		var ne4 = this.data.dateTimeArray1[3][this.data.dateTime1[3]];
		var ne5 = this.data.dateTimeArray1[4][this.data.dateTime1[4]];
		var str = ne1 + '/' + ne2 + '/' + ne3;
		this.setData({
			ne: Number(new Date(str).getTime()) + Number(ne5) * 60000 + Number(ne4) * 3600000
		})
		console.log(this.data.ne);

		var res=await cherckMineInfo();
		console.log(res.data);
		this.setData({
			//wx_no:res.data.wechat_alian_no,
			wx_no_de:res.data
		})

		  this.initWeCropper()

	},
	  initWeCropper() {
	    const {
	      cropperOpt
	    } = this.data
	    this.cropper = new WeCropper(cropperOpt)
	      .on('ready', (ctx) => {})
	      .on('beforeImageLoad', (ctx) => {
	        wx.showToast({
	          title: '上传中',
	          icon: 'loading',
	          duration: 20000
	        })
	      })
	      .on('imageLoad', (ctx) => {
	        wx.hideToast()
	      })
	  },

	  tip_text_handler(e){

		// 浏览器打开管理地址
	   let tip_text=e.currentTarget.dataset.tip_text
	   
	   util.tip_func(tip_text)
   
	 },
  chooseimg() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          showWeCropper: true
        });
        this.cropper.pushOrign(res.tempFilePaths[0]);
      }
    })
  },
    getCropperImage() {
      this.cropper.getCropperImage((res) => {
		if(this.data.image_index==0){
			this.setData({
			  showWeCropper: false,
			  liveImg: res,
			})
		}else{
			this.setData({
			  showWeCropper: false,
			  shareImg: res,
			})
		}
        
      })
    },
	async judgeAuth() {
		var that = this;
		if (!this.data.wx_no) {
			wx.showToast({
				icon: 'none',
				title: '请输入您的微信号',
			})
			return;
		}
		this.setData({
			is_go_auth: true
		})
		//await setData(dataKey.wx_no,this.data.wx_no);
		const {
			data
		} = await hostCheck({
			wechat_no: this.data.wx_no
		})
		console.log(data);
		this.setData({
			is_go_auth: false
		})
		if (data != 1) {
			wx.showModal({
				title: '您还没有微信直播认证',
				content: '',
				cancelText: '取消',
				confirmText: '去认证',
				confirmColor: '#F95A4B',
				success(res) {
					if (res.confirm) { //确认
						that.is_back = true
						// wx.navigateToMiniProgram({
						// 	appId: 'wxcbbd86b156ae4441',
						// })
						console.log(data);
						var data_img=[];
						data_img.push(data);
						 wx.previewImage({
						    current: data, 
						    urls: data_img
						 })
					} else if (res.cancel) { //取消

					}
				}
			})
			return;
		}
		// await setData(dataKey.is_host,data);
		this.setData({
			is_host: data
		})
		refreshInfo({
			anchor_wechat_no: this.data.wx_no
		}); // 修改主播微信号 非当前用户微信号
	},
	async sub_anchor_check(){
			// 主播副微信号认证,检测
		
			if(this.data.sub_wx_no==''){

				return 
			}

			let that=this

			wx.showLoading({
			  title: '实名检测中',
			})
		const {data} = await hostCheck({
			wechat_no:this.data.sub_wx_no
		})

		wx.hideLoading({
		  success: (res) => {},
		})

		if(data!=1){
           this.setData({
			  sub_anchor_qr:data
		   })


		   
		   wx.showModal({
			 title:'未实名',
			 content:"发送认证码给副微信区认证吧?",

			 success:function(res){
				if(res.confirm){
					var data_img=[];
					data_img.push(that.data.sub_anchor_qr);
					wx.previewImage({
						current: data_img[0], 
						urls: data_img
					})

				}
			 }
		   })
		}else{
			this.setData({
				sub_anchor_disable:true,
				sub_is_authed:true,
				sub_anchor_qr:''
			})
		
			wx.showToast({
			  title: '已认证',
			})
		}
			

	},
	
	showAuthQr(e){
		// 显示 副微信号认证码
		let  sub_qr= e.currentTarget.dataset.src

		var data_img=[];
		data_img.push(sub_qr);
		wx.previewImage({
			current: sub_qr, 
			urls: data_img
		})

	},


	changeDateTime1(e) {
		// console.log(e);

		//var date=new Date().getTime();
		var ne1 = this.data.dateTimeArray1[0][this.data.dateTime1[0]];
		var ne2 = this.data.dateTimeArray1[1][this.data.dateTime1[1]];
		var ne3 = this.data.dateTimeArray1[2][this.data.dateTime1[2]];
		var ne4 = this.data.dateTimeArray1[3][this.data.dateTime1[3]];
		var ne5 = this.data.dateTimeArray1[4][this.data.dateTime1[4]];
		var str = ne1 + '/' + ne2 + '/' + ne3;
		//console.log(str);
		//    console.log(new Date().getTime());
		// console.log(Number(new Date(str).getTime())+Number(ne5)*60000+Number(ne4)*3600000);   
		let timeDur2 = (Number(new Date(str).getTime()) + Number(ne5) * 60000 + Number(ne4) * 3600000) - Number(new Date().getTime())
		this.setData({
			ne: Number(new Date(str).getTime()) + Number(ne5) * 60000 + Number(ne4) * 3600000
		})
		console.log(timeDur2);

		if (timeDur2 < 600000) {
			wx.showToast({
				icon: 'none',
				title: '开播时间至少在10分钟后',
			})
			return;
		}
		this.setData({
			dateTime1: e.detail.value
		});
	},
	changeDateTimeColumn1(e) {
		var arr = this.data.dateTime1,
			dateArr = this.data.dateTimeArray1;

		arr[e.detail.column] = e.detail.value;
		dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

		console.log(arr);
		this.setData({
			dateTimeArray1: dateArr,
			dateTime1: arr
		});
	},

	toggleShow3(e) {
		this.type = e.currentTarget.dataset.type;
		this.setData({
			timeShow3: true
		});
	},
	bindDateChange: function(e) {
		console.log('picker发送选择改变，携带值为', e.detail.value)
		this.setData({
			date: e.detail.value
		})
	},
	timeSelect3(e) {
		let {
			date,
			dateTimeStr
		} = e.detail;
		if (this.type == 'start') {
			let timeDur2 = date.getTime() - this.data.rangeStart;
			if (timeDur2 < 600000) {
				wx.showToast({
					icon: 'none',
					title: '开播时间至少在10分钟后',
				})
				return;
			}
		}

		/*
		 后台默认 4小时
		if(this.data.timeStr3&&this.type == 'end'){
		  let timeDur = date.getTime() - this.data.time3;
		  if(timeDur<1800000){
		    wx.showToast({
		      icon:'none',
		      title: '开播时间和结束时间间隔不得短于30分钟',
		    })
		    return;
		  }
		} else if (this.data.timeStr4&&this.type == 'start'){
		  let timeDur1 =  this.data.time4 - date.getTime();
		  if(timeDur1<1800000){
		    wx.showToast({
		      icon:'none',
		      title: '开播时间和结束时间间隔不得短于30分钟',
		    })
		    return;
		  }
		}*/
		if (this.type == 'start') {
			this.setData({
				time3: date.getTime(),
				timeStr3: dateTimeStr
			});
		} else {
			this.setData({
				time4: date.getTime(),
				timeStr4: dateTimeStr
			});
		}
	},
	bindPickerChange(e) {
		this.setData({
			live_index: e.detail.value
		})
	},
	changeDateTimeColumn1(e) {
		console.log(e);
		var arr = this.data.dateTime1,
			dateArr = this.data.dateTimeArray1;

		arr[e.detail.column] = e.detail.value;
		dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

		// this.setData({ 
		//  dateTimeArray1: dateArr,
		//  dateTime1: arr
		// });
	},
	changeInput(e) {
		this.setData({
			wx_no: e.detail.value,
			is_host: 0
		})
	},
	changeInput_1(e) {
		this.setData({
			sub_wx_no: e.detail.value,
		})

	
	},
	changeInputTitle(e) {
		if(e.detail.value.length>17||e.detail.value.length<3){
		  wx.showToast({
		    icon:'none',
		    title: '至少输入6个字至多输入17个字',
		  })
		  return;
		}
		this.setData({
			live_title: e.detail.value
		})
	},
	  touchStart(e) {
	    this.wecropper.touchStart(e)
	  },
	  touchMove(e) {
	    this.wecropper.touchMove(e)
	  },
	  touchEnd(e) {
	    this.wecropper.touchEnd(e)
	  },
	  // upLoad(e){
		 //  var that = this;
		 //  var type = e.currentTarget.dataset.type
		 //  this.is_upload = true // 表示正在上传， 控制按钮点击
		 //  wx.chooseImage({
		 //  		count: 1,
		 //  		sizeType: ['original', 'compressed'],
		 //  		sourceType: ['album', 'camera'],
		 //  		success:function(res) {
					
			// 		that.is_upload = false;
					
			// 		that.setData({
			// 			image_index:0,
			// 			is_load_live_cover: true,
			// 			liveImg:res.tempFilePaths[0]
			// 		});
					
			// 		console.log(res.tempFilePaths[0]);
					
			// 		// that.cropper.pushOrign(res.tempFilePaths[0]);
			// 	},
		 //  })
	  // },
	  // upLoad1(e){
	  // 		  var that = this;
	  // 		  var type = e.currentTarget.dataset.type
	  // 		  this.is_upload = true // 表示正在上传， 控制按钮点击
	  // 		  wx.chooseImage({
	  // 		  		count: 1,
	  // 		  		sizeType: ['original', 'compressed'],
	  // 		  		sourceType: ['album', 'camera'],
	  // 		  		success:function(res) {
						
			// 			that.is_upload = false;
	  // 					that.setData({
	  // 						showWeCropper: true,
	  // 						image_index:1,
			// 				test1: -1
	  // 					});
	  					
	  // 					that.cropper.pushOrign(res.tempFilePaths[0]);
	  // 				},
	  // 		  })
	  // },
	upLoad(e) { // 上传封面图片何直播间分享图片
		var that = this;
		var type = e.currentTarget.dataset.type
		this.is_upload = true // 表示正在上传， 控制按钮点击
		wx.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: async function(res) {
				const tempFilePaths = res.tempFilePaths
				that.is_upload = false;
				
				// this.setData({
				//   showWeCropper: true
				// });
				
				if (type == 'live') {
					that.setData({
						is_load_live_cover: true // 封面正在上传
					})
				} else {
					that.setData({
						is_load_share_cover: true // 分享封面正在上传
					})
				}
                
				//this.cropper.pushOrign(res.tempFilePaths[0]);
				
				const {
					data
				} = await uploadFile(tempFilePaths[0]) //上传图片
				if (type == 'live') {
					that.setData({
						is_load_live_cover: false,
						liveImg: data.indexOf('http') > -1 ? data : "http:" + data
					})
				} else {
					that.setData({
						is_load_share_cover: false,
						shareImg: data.indexOf('http') > -1 ? data : "http:" + data,
						test1: -1
					})
				}
			},
		})
	},
	load(e) {
		console.log(e);
		var id = e.currentTarget.dataset.id
		var img = e.currentTarget.dataset.img
		this.setData({
			test1: id,
			img1: img
		})
	},
	async submit() { // 创建直播 


		if(this.data.sub_wx_no!='' && !this.data.sub_is_authed){

			wx.showToast({
				icon: 'none',
				title: '请确认副微信号实名认证',
			})
			return
		}

		if (!this.data.live_title) {
			wx.showToast({
				icon: 'none',
				title: '请输入直播间标题',
			})
			return
		}
		if (Number(this.data.ne) - Number(new Date().getTime()) < 600000) {
			wx.showToast({
				icon: 'none',
				title: '开播时间至少在10分钟后',
			})
			return
		}
		if (this.data.live_title.length > 17 || this.data.live_title.length < 3) {

			wx.showToast({
				icon: 'none',
				title: '直播标题长度应在[3~17]个字符',
			})
			return
		}

		if (this.data.live_index == -1) {
			wx.showToast({
				icon: 'none',
				title: '请选择直播商品类目',
			})
			return
		}
		if (!this.data.liveImg && this.data.test1 == '') {
			wx.showToast({
				icon: 'none',
				title: '请上传直播封面',
			})
			return
		}

		wx.showLoading({
			title: '正在创建直播',
		})
		var img = "";
		if (this.data.test1 == -1) {
			img = this.data.shareImg
		} else {
			img = this.data.default_share_imgs[this.data.test1]
		}

		var ne1 = this.data.dateTimeArray1[0][this.data.dateTime1[0]];
		var ne2 = this.data.dateTimeArray1[1][this.data.dateTime1[1]];
		var ne3 = this.data.dateTimeArray1[2][this.data.dateTime1[2]];
		var ne4 = this.data.dateTimeArray1[3][this.data.dateTime1[3]];
		var ne5 = this.data.dateTimeArray1[4][this.data.dateTime1[4]];
		var str = ne1 + '-' + ne2 + '-' + ne3 + ' ' + ne4 + ':' + ne5 + ':00';


		console.log(this.data.live_title, this.data.live_list[this.data.live_index].id, str, this.data.liveImg, img);
		const {
			data
		} = await creatLive({
			name: this.data.live_title,
			cate: this.data.live_list[this.data.live_index].id,
			start_time: str,
			end_time: '',
			cover_img: this.data.liveImg,
			share_img: img,
			anchor_wechat_name: this.data.userInfo.wx_nickname,
			anchor_wechat_no: this.data.wx_no,
			sub_anchor_wechat_no: this.data.sub_wx_no,
		})
		wx.hideLoading();
		wx.navigateTo({
			url: '/pages/module/addProduct/addProduct?id=' + data + '&Back=gg',
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: async function() {

		if(this.data.wx_no!=''){
			
			const {
				data
			} = await hostCheck({
				wechat_no: this.data.wx_no
			})
			console.log(data);
			await setData(dataKey.is_host, data);
			this.setData({
				is_host: data
			})
		}
		const opt = await visitList({
			opt: 3
		});
		console.log(opt);
		this.setData({
			default_share_imgs: opt.data
		});
	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: async function() {
		

	},
	openProductAddHandler: async function() {

		// 打开 直播添加产品页面 用于测试

		let live_id = this.data.test_live_id
		wx.navigateTo({
			url: '/pages/module/addProduct/addProduct?id=' + live_id,
		})
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
